package com.newdjk.newdoctor.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.google.gson.Gson;
import com.newdjk.newdoctor.BuildConfig;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.base.BasicFragment;
import com.newdjk.newdoctor.constants.EnvironmentManager;
import com.newdjk.newdoctor.entity.ShareWXEntity;
import com.newdjk.newdoctor.ui.WebViewActivity;
import com.newdjk.newdoctor.utils.Contants;
import com.newdjk.newdoctor.utils.Event;
import com.newdjk.newdoctor.utils.RxBus;
import com.newdjk.newdoctor.utils.SpUtils;
import com.newdjk.newdoctor.utils.ToastUtil;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

public class FindForFragment extends BasicFragment implements IWXAPIEventHandler {


    private static final String TAG = "FindForFragment";
    @BindView(R.id.test_bridge_webView)
    BridgeWebView testBridgeWebView;

    private ShareWXEntity mShareWXEntity;
    private Gson mGson = new Gson();
    private Dialog mDialog;
    private View mInflate;
    private View mFriend;
    private View mZoom;
    private View mTvCancel;
    private IWXAPI iwxapi;
    private String shareTitle;
    private String Url;
    private Observable<Boolean> loginObservable;

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        String result;
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                result = "分享成功";
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = "取消分享";
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = "分享被拒绝";
                break;
            default:
                result = "发送返回";
                break;
        }
        Toast.makeText(getContext(), result, Toast.LENGTH_SHORT).show();
    }


    enum SHARE_TYPE {Type_WXSceneSession, Type_WXSceneTimeline}

    @Override
    protected int initViewResId() {
        return R.layout.fragment_find;
    }

    @Override
    protected void initView() {

        initUrl();
        loginObservable = RxBus.get().register(Event.Login_success);

        loginObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                // QueryDoctorIdentify();
                testBridgeWebView.reload();
            }
        });

        iwxapi = WXAPIFactory.createWXAPI(getContext(), Contants.WEIXIN_APP_ID, false);
        iwxapi.handleIntent(getActivity().getIntent(), this);
        testBridgeWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        testBridgeWebView.clearCache(true);
        testBridgeWebView.clearHistory();
        testBridgeWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        testBridgeWebView.getSettings().setSupportZoom(true);
        testBridgeWebView.getSettings().setJavaScriptEnabled(true);
        testBridgeWebView.getSettings().setBuiltInZoomControls(true);
        testBridgeWebView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
        testBridgeWebView.getSettings().setUseWideViewPort(true);
        testBridgeWebView.getSettings().setTextZoom(100);  //消除系统大小的设置对webview字体大小的影响
        testBridgeWebView.getSettings().setDomStorageEnabled(true); //解决加载不出webview白屏问题
        testBridgeWebView.getSettings().setDatabaseEnabled(true);
        testBridgeWebView.getSettings().setAllowFileAccess(true);
        testBridgeWebView.getSettings().setAppCacheEnabled(true);
        testBridgeWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        testBridgeWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        testBridgeWebView.setBackgroundColor(0); // 设置背景色
        testBridgeWebView.loadUrl(Url + "collegeList");
        sendNative();
    }

    private void initUrl() {

        if (BuildConfig.DEBUG) { //测试环境
            //判断是正式环境还是测试环境
            if (EnvironmentManager.isDebug(getContext())) {
                Url = "file:///android_asset/test/index.html#/";
            } else {
                Url = "file:///android_asset/online/index.html#/";

            }


        } else { //正式环境
            Url = "file:///android_asset/online/index.html#/";
        }
    }

    public void sendNative() {
//        String userInfo = "";
//        userInfo = SpUtils.getString(Contants.LoginJson);
//        testBridgeWebView.callHandler("UserInfo", userInfo, new CallBackFunction() {
//            @Override
//            public void onCallBack(String data) {
//                Log.i("发现界面", data);
//
//            }
//
//        });
//
//        Log.i("登录信息", "LoginJson=" + userInfo);
        //H5主动获取登录数据
        testBridgeWebView.registerHandler("GetUserInfo", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                String userInfo = "";

                userInfo = SpUtils.getString(Contants.LoginJson);

                Log.i("zdp", userInfo + "");
                function.onCallBack(userInfo);
            }
        });

        //H5分享到微信或者朋友圈
        testBridgeWebView.registerHandler("ShareToWx", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

//                let url = `${introAdmin}index.html#/collegeArtDetail?aId=${this.info.ArticleId}&CKTAG=mta_share.wechat_moments`
//            let msg = {
//                title:this.info.ArticleTitle || "",
//                des:this.info.Summary || "",
//                img:this.info.ImagePath || "",
//                link:redirect + encodeURIComponent(url)
//            }
//            this.$bridge.callhandler('ShareToWx', JSON.stringify(msg))
                Log.d(TAG, "分享" + data);

                mShareWXEntity = mGson.fromJson(data, ShareWXEntity.class);

                showBottomDialog();

            }
        });

        //内部链接跳转
        testBridgeWebView.registerHandler("toInnerLink", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //根跳转认证
                Intent renzheng = new Intent(getContext(), WebViewActivity.class);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String url = jsonObject.getString("url");
                    renzheng.putExtra("innerLink", url);
                    renzheng.putExtra(Contants.TYPE, 21);
                    startActivity(renzheng);
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtil.setToast("数据解析异常");
                }

            }
        });
    }

    public void showBottomDialog() {
        mDialog = new Dialog(getContext(), R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        mInflate = LayoutInflater.from(getContext()).inflate(R.layout.dialog_share, null);
        //初始化控件
        mFriend = mInflate.findViewById(R.id.mWechatFriend);
        mZoom = mInflate.findViewById(R.id.mWechatZone);
        mTvCancel = mInflate.findViewById(R.id.mCancel);
        mFriend.setOnClickListener(this);
        mZoom.setOnClickListener(this);
        mTvCancel.setOnClickListener(this);
        //将布局设置给Dialog
        mDialog.setContentView(mInflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 10;//设置Dialog距离底部的距离
//       将属性设置给窗体
        lp.width = LinearLayout.LayoutParams.MATCH_PARENT;
        dialogWindow.setAttributes(lp);
        mDialog.show();//显示对话框
    }


    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void otherViewClick(View view) {
        switch (view.getId()) {

            case R.id.btn_share:
                showBottomDialog();

                break;
            case R.id.mWechatFriend:
                share(SHARE_TYPE.Type_WXSceneSession);
                mDialog.dismiss();
                break;
            case R.id.mWechatZone:
                share(SHARE_TYPE.Type_WXSceneTimeline);
                mDialog.dismiss();
                break;
            case R.id.mCancel:
                if (mDialog.isShowing())
                    mDialog.dismiss();
                break;
        }
    }

    private void share(SHARE_TYPE type) {
           /*  FileInputStream fis = null;
        try {
            fis = new FileInputStream(mSdPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (fis == null){
            return;
        }
        Bitmap thumb  = BitmapFactory.decodeStream(fis);*/

        WXWebpageObject webpageObject = new WXWebpageObject();
        // mSendGoodsEntity = mGson.fromJson(sharedata, SendGoodsEntity.class);
        if (mShareWXEntity != null) {
            shareTitle = mShareWXEntity.getTitle();
            if (!TextUtils.isEmpty(mShareWXEntity.getLink())) {
                webpageObject.webpageUrl = mShareWXEntity.getLink();
            } else {
                webpageObject.webpageUrl = "http://www.newstartclinic.com/";
            }
        } else {
            webpageObject.webpageUrl = "http://www.newstartclinic.com/";
            return;
        }
        //用WXWebpageObject对象初始化一个WXMediaMessage，天下标题，描述
        final WXMediaMessage msg = new WXMediaMessage(webpageObject);

        if (TextUtils.isEmpty(shareTitle)) {
            msg.title = "芸医生向您推荐";
        } else {
            msg.title = shareTitle;
        }
        String des = mShareWXEntity.getDes();
        msg.description = TextUtils.isEmpty(des) ? "" : des;


        if (!TextUtils.isEmpty(mShareWXEntity.getImg())) {

            //  Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.icon);
            loading(true);
            Glide.with(getContext())
                    .asBitmap()
                    .load(mShareWXEntity.getImg()).into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                    loading(false);
                    Bitmap scaledBitmap = Bitmap.createScaledBitmap(resource, 200, 200, true);

                    msg.setThumbImage(scaledBitmap);
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = String.valueOf(System.currentTimeMillis());
                    req.message = msg;
                    switch (type) {
                        case Type_WXSceneSession:
                            req.scene = SendMessageToWX.Req.WXSceneSession;
                            break;
                        case Type_WXSceneTimeline:
                            req.scene = SendMessageToWX.Req.WXSceneTimeline;
                            break;
                    }
                    iwxapi.sendReq(req);
                }

                @Override
                public void onLoadFailed(@Nullable Drawable errorDrawable) {
                    super.onLoadFailed(errorDrawable);
                    loading(false);
                    Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.icon);
                    msg.setThumbImage(thumb);
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = String.valueOf(System.currentTimeMillis());
                    req.message = msg;
                    switch (type) {
                        case Type_WXSceneSession:
                            req.scene = SendMessageToWX.Req.WXSceneSession;
                            break;
                        case Type_WXSceneTimeline:
                            req.scene = SendMessageToWX.Req.WXSceneTimeline;
                            break;
                    }
                    iwxapi.sendReq(req);

                }
            });

        } else {
            Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.icon);
            msg.setThumbImage(thumb);
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;

            switch (type) {
                case Type_WXSceneSession:
                    req.scene = SendMessageToWX.Req.WXSceneSession;
                    break;
                case Type_WXSceneTimeline:
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                    break;
            }
            iwxapi.sendReq(req);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(Event.Login_success, loginObservable);
    }

}
